package com.ggkt.common.utils;

import org.apache.commons.lang3.StringUtils;

public class PreventInjectionUtil {

    /**
     * 转义可能的注入字符
     */
    public static String escape(String content) {

        if (content == null) {
            return null;
        }
        if (StringUtils.isBlank(content)) {
            return "";
        }
        // content = content.replaceAll("&", "&amp;");
        content = content.replaceAll("<", "&lt;");
        content = content.replaceAll(">", "&gt;");
        content = content.replaceAll("\"", "&quot;");
        content = content.replaceAll("'", "&apos;");
        return content;
    }

    /**
     * 转义可能的注入字符, 用于将内容直接渲染的情况
     */
    public static String escape4Render(String content) {

        if (content == null) {
            return null;
        }
        if (StringUtils.isBlank(content)) {
            return "";
        }
        // 将script 替换成&lt;script&gt; ,将 on 替换成 ｏn
        String contentLower = content.toLowerCase();
        if (contentLower.indexOf("<script>") > -1 || contentLower.indexOf("</script>") > -1) {
            content = contentLower.replaceAll("<script>", "&lt;script&gt;");
            content = content.replaceAll("</script>", "&lt;/script&gt;");
        }
        if (contentLower.indexOf("<iframe>") > -1 || contentLower.indexOf("</iframe>") > -1) {
            content = contentLower.replaceAll("<iframe>", "&lt;iframe&gt;");
            content = content.replaceAll("</iframe>", "&lt;/iframe&gt;");
        }
        boolean flag = contentLower.indexOf("onerror") > -1 || contentLower.indexOf("onclick") > -1
            || contentLower.indexOf("onfocus") > -1 || contentLower.indexOf("onblur") > -1
            || contentLower.indexOf("onchange") > -1 || contentLower.indexOf("ondblclick") > -1
            || contentLower.indexOf("onabort") > -1 || contentLower.indexOf("onkeydown") > -1
            || contentLower.indexOf("onkeypress") > -1 || contentLower.indexOf("onkeyup") > -1
            || contentLower.indexOf("onload") > -1 || contentLower.indexOf("onmousedown") > -1
            || contentLower.indexOf("onmousemove") > -1 || contentLower.indexOf("onmouseout") > -1
            || contentLower.indexOf("onmouseover") > -1 || contentLower.indexOf("onmouseup") > -1
            || contentLower.indexOf("onunload") > -1;
        if (flag) {
            content = contentLower.replaceAll("on", "ｏn");
        }
        return content;
    }

}